package znet

import (
	"fmt"
	"net"
	"zinx/utils"
	"zinx/ziface"
)

/// 实现IServer接口，定义的服务器实现模块类
type Server struct {
	Name      string
	IpVersion string
	IP        string
	Port      int
	Router    ziface.IRouter
}

func (server *Server) Start() {
	fmt.Printf("[Start] %s %s:%d\n", server.Name, server.IP, server.Port)

	go func() {
		/// 1 创建一个socket句柄
		sock, err := net.ResolveTCPAddr(server.IpVersion, fmt.Sprintf("%s:%d", server.IP, server.Port))
		if err != nil {
			fmt.Println("ResolveTCPAddr err : ", err)
			return
		}

		/// 2. 监听ip 端口
		listen, err := net.ListenTCP(server.IpVersion, sock)
		if err != nil {
			fmt.Println("listenTcp err : ", err)
			return
		}

		var cid uint32
		cid = 0

		/// 3. 阻塞
		for {
			conn, err := listen.AcceptTCP()
			if err != nil {
				fmt.Println("Accept err : ", err)
				continue
			}

			dealConn := NewConnection(conn, cid, server.Router)
			cid++

			go dealConn.Start()
		}
	}()
}

func (server *Server) Stop() {

}

func (server *Server) Serve() {
	/// 开始服务端
	server.Start()

	/// 阻塞
	select {}
}

/// 添加Router路由的方法， 提供链接处理业务的方法
func (server *Server) AddRouter(router ziface.IRouter) {
	server.Router = router
}

func NewSever() ziface.IServer {
	s := &Server{
		Name:      utils.GlobalObject.Name,
		IpVersion: utils.GlobalObject.Version,
		IP:        utils.GlobalObject.Host,
		Port:      utils.GlobalObject.TcpPort,
		Router:    nil,
	}

	return s
}
